package com.stack.search.service.impl;

import com.stack.common.utils.thread.AppThreadLocalUtil;
import com.stack.model.common.dtos.ResponseResult;
import com.stack.model.user.pojos.ApUser;
import com.stack.search.pojos.ApHotSearch;
import com.stack.search.service.ApHotSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
@Slf4j
public class ApHotSearchServiceImpl implements ApHotSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询热搜索历史
     */
    @Override
    public ResponseResult findHotSearch() {

        ApUser user = AppThreadLocalUtil.getUser();
        Integer userId = user.getId();

//        long time = 60 * 60 * 1000;//30分钟
        long time = 60 * 60 * 1000 * 24;//1天

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.HOUR_OF_DAY, +8);

        Date now = calendar.getTime();
        Date start = new Date(now.getTime() - time);

        //mongo取数据时间格式转换
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
//        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
//        String startTime = sdf.format(start);
//        String endTime = sdf.format(now);

        //根据用户查询数据，某一时刻一天前的热词
        List<ApHotSearch> apHotSearchList = mongoTemplate.find(Query.query(Criteria.where("createdTime").gte(start).lte(now)), ApHotSearch.class);
//        List<ApHotSearch> apHotSearchLists = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)), ApHotSearch.class);

        // TODO 过滤对象，
        ArrayList<ApHotSearch> apHotSearches = new ArrayList<>();
        ArrayList<String> list = new ArrayList<>();
        for (ApHotSearch apHotSearch : apHotSearchList) {
            apHotSearches.add(apHotSearch);
            list.add(apHotSearch.getHotKeyword());
        }

        Set<ApHotSearch> set = new HashSet<>();

        log.info("apHotSearchList:{}", apHotSearchList);
//        log.info("apHotSearchLists:{}", apHotSearchLists);

        return ResponseResult.okResult(apHotSearches);
    }
}
